package com.yunnuo.monitor.job.controller;

import com.yunnuo.monitor.job.entity.MonJob;
import com.yunnuo.monitor.job.manager.QuartzManager;
import com.yunnuo.monitor.job.service.IJobService;
import com.yunnuo.system.comm.controller.BaseController;
import com.yunnuo.system.comm.util.Empty;
import com.yunnuo.system.comm.util.ResultData;
import com.yunnuo.system.comm.util.page.TableDataInfo;
import com.yunnuo.system.dict.entity.DictData;
import com.yunnuo.system.dict.service.IDictDataService;
import com.yunnuo.system.users.entity.PageParams;
import net.sf.json.JSON;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.quartz.Job;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author 魏洪福（15064000912@163.com）
 * @create 2018-09-25-13:42
 */
@Controller
@RequestMapping("monitor/job")
public class JobController extends BaseController {

    private String prefix = "monitor/job";
    @Autowired
    private IJobService jobService;

    @Autowired
    private IDictDataService dictDataService;
    @Autowired
    private QuartzManager quartzManager;


    @GetMapping()
    public String job()
    {
        return prefix + "/job";
    }

    /**
     * 分页查询
     * @param pageParams
     * @return
     */
    @RequiresPermissions("monitor:job:list")
    @GetMapping("/list")
    @ResponseBody
    public TableDataInfo list(PageParams pageParams)
    {
        return jobService.selecJobByPageParams(pageParams,startPage(pageParams));
//   ========= 另外一个方式实现=========
//        List list =null;
//        try {
//          list=  this.quartzManager.getAllJob();
//        } catch (SchedulerException e) {
//            e.printStackTrace();
//        }
//        return this.getDataTable(list);
    }


    /**
     * 修改启用/停用状态
     * @param job   status 0正常 1暂停
     * @return  1-成功
     */
    @RequiresPermissions("monitor:job:save")
    @PostMapping("/save")
    @ResponseBody
    public JSON save(MonJob job)
    {
        ResultData data = new ResultData();
        try{
            if(Empty.isEmpty(job.getId())){
                job.setCreateTime(new Date());
                job.setLoginName(this.getLoginName());
                job.setUpdateTime(new Date());
            }else{
                MonJob job2= jobService.findVO(job.getId());
                job.setCreateTime(job2.getCreateTime());
                job.setUpdateTime(new Date());
                job.setLoginName(job2.getLoginName());
            }
            job =jobService.save(job);
            if(null==job || "".equals(job.getId())){
                throw new RuntimeException("JobController.save(job):保存失败");
            }else{
                if(job.getStatus().equals("on")){
                    this.quartzManager.addJob(job);
                }
            }
            data.setStat(ResultData.STAT_SUCCESS);
            data.setMessage("操作成功！");
        }catch (Exception e){
            e.printStackTrace();
            data.setStat(ResultData.STAT_FAILURE);
            data.setMessage("操作失败！");
        }

        return data.toJson();
    }
    /**
     * 开启一个任务
     * @param id
     * @return
     */
    @PostMapping("/start/{id}")
    @ResponseBody
    public JSON start(@PathVariable("id") String id)
    {
        ResultData data = new ResultData();
        try{
            MonJob job= jobService.findVO(id);
            job.setUpdateTime(new Date());
            job.setStatus("on");
            job =jobService.save(job);
            this.quartzManager.resumeJob(job);
            data.setStat(ResultData.STAT_SUCCESS);
            data.setMessage("操作成功！");
        }catch (Exception e){
            e.printStackTrace();
            data.setStat(ResultData.STAT_FAILURE);
            data.setMessage("操作失败！");
        }

        return data.toJson();
    }
    /**
     * 停止一个任务
     * @param id
     * @return
     */
    @PostMapping("/stop/{id}")
    @ResponseBody
    public JSON stop(@PathVariable("id") String id)
    {
        ResultData data = new ResultData();
        try{
            MonJob job= jobService.findVO(id);
            job.setUpdateTime(new Date());
            job.setStatus("no");
            job =jobService.save(job);
            this.quartzManager.pauseJob(job);
            data.setStat(ResultData.STAT_SUCCESS);
            data.setMessage("操作成功！");
        }catch (Exception e){
            e.printStackTrace();
            data.setStat(ResultData.STAT_FAILURE);
            data.setMessage("操作失败！");
        }

        return data.toJson();
    }

    @RequiresPermissions("monitor:job:add")
    @GetMapping("/add")
    public String add(Model model)
    {
        List<DictData> dictData=dictDataService.findList();
        model.addAttribute("dict", dictData);
        return prefix + "/add";
    }

    /**
     * 修改
     */
    @RequiresPermissions("monitor:job:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") String id, Model model)
    {
        MonJob job=jobService.findVO(id);
        model.addAttribute("job", job);
        return prefix + "/edit";
    }


    @RequiresPermissions("monitor:job:remove")
    @RequestMapping("/remove/{id}")
    @ResponseBody
    public JSON remove(@PathVariable("id")String id)
    {
        ResultData data = new ResultData();
        try{

            MonJob job=jobService.findVO(id);
            if (job == null)
            {
                data.setStat(ResultData.STAT_FAILURE);
                data.setMessage("定时任务不存在！");
            }
            this.quartzManager.deleteJob(job);
            jobService.deleteVo(id);
            data.setStat(ResultData.STAT_SUCCESS);
            data.setMessage("操作成功！");
        }catch (Exception e){
            data.setStat(ResultData.STAT_FAILURE);
            data.setMessage("删除失败！");
        }
        return data.toJson();
    }



    @GetMapping("/test")
    @ResponseBody
    public JSON list()
    {
    MonJob job =new MonJob();
        job.setTaskName("job1");
        job.setMethod("com.yunnuo.monitor.job.Test");
        job.setOperation("0/1 * * * * ?");
        quartzManager.addJob(job);
        return null;
    }

}
